<?php

namespace app\admin\controller\oil;

use addons\sum\library\Export;
use app\admin\controller\sum\Base;
use app\admin\model\oil\order\Order as OrderModel;
use app\admin\model\User as UserModel;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 发票管理
 *
 * @icon fa fa-circle-o
 */
class WorkOrder extends Base
{

    /**
     * WorkOrder模型对象
     * @var \app\admin\model\oil\WorkOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\oil\WorkOrder;
        $this->model_log = new \app\admin\model\oil\WorkOrderLog;

    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null);

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            $this->success('工单列表', null, $result);
        }
        return $this->view->fetch();
    }

    public function export()
    {
        list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null);
        $expCellName = [
            'id' => 'ID',
            'user_name' => '用户姓名',
            'user_phone' => '用户账号电话',
            'order_sn' => '加油票订单号',
            'store_name' => '加油站名',
            'need_departments_text' => '协助部门处理',//需要处理
            'visittime_text' => '登记时间',
            'huifu_hour' => '回复处理时间',
            'status_text' => '工单状态',
            'log_text' => '登记|回访信息',
        ];
        $export = new Export();
        $spreadsheet = null;
        $sheet = null;

        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit(($i * $page_size), $page_size)
                ->select();

            $list = collection($list)->toArray();
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('工单列表-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page' => $page,
                'current_total' => $current_total,
                'is_last_page' => $is_last_page
            ]);
        }
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $params = json_decode($params['data'], true);
                //处理数据
//                if(is_array($params['need_departments'])){
//                    $params['need_departments']=json_encode($params['need_departments']);
//                }
//                if($params['visittime']){
//                    $params['visittime']=strtotime($params['visittime']);
//                }

                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    // 增加记录
                    $log_data['work_order_id']=$this->model['id'];
                    $log_data['event']='add';
                    $log_data['content']=$params['content'];
                    $log_data['visittime']=$params['visittime'];
                    $log_data['oper_name']=$params['oper_name'];
                    $log_data['work_type']=$params['work_type'];
                    $log_data['work_type_title']=$params['work_type_title']??'';
                    $result_log = $this->model_log->save($log_data);
                    Db::commit();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("添加成功");
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = json_decode($params['data'], true);
                //处理数据

                if($row['status']!='1'){//协助工单不能修改登记时间和回复时间
                    unset($params['visittime']);
                    unset($params['huifu_hour']);
                }else{//二次登记如果不填回访时间调用登记时间
                    if(!$params['re_visittime']){
                        $params['re_visittime']=$params['visittime'];
                    }
                }
//                if($params['visittime']){
//                    $params['visittime']=strtotime($params['visittime']);
//                }
//                if($params['re_visittime']){
//                    $params['re_visittime']=strtotime($params['re_visittime']);
//                }
                $result = false;
                Db::startTrans();
                try {
                    $row->allowField(true)->save($params);
                    $row->save();
                    //如何传回访内容的话
                    if($params['content']){
                        // 增加记录
                        $log_data['work_order_id']=$row['id'];
                        $log_data['event']='edit';
                        $log_data['content']=$params['content'];
                        $log_data['visittime']=$params['re_visittime'];
                        $log_data['oper_name']=$params['re_oper_name'];
                        $log_data['work_type']=$params['re_work_type'];
                        $log_data['work_type_title']=$params['re_work_type_title']??'';
                        $result_log = $this->model_log->save($log_data);
                    }
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->assignconfig("row", $row);
        return $this->view->fetch();
    }

    /**
     * 检测订单号
     * @return void
     */
    public function cheakOrderSn()
    {
        $order_sn=$this->request->post('order_sn');
        $order=OrderModel::where('order_sn',$order_sn)->find();
        if($order){
            $order_user=UserModel::where('id',$order['user_id'])->find();
        }
        $return['store_name'] = $order['store_name']??'';
        $return['user_phone'] = $order_user['mobile']??'';
        $this->success('操作成功', null, $return);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
